package com.yjh.server.task;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.yjh.pojo.entity.ReservationMain;
import com.yjh.server.mapper.ReservationMainMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

@Component
public class ReservationOverdueTask {
    @Autowired
    private ReservationMainMapper reservationMainMapper;

    //0秒 0分开始30分钟执行一次 任意小时执行 任意日期执行 任意月份执行 不指定星期
    @Scheduled(cron = "0 0/50 * * * ?")
    public void handleOverdueReservation(){
//        LocalDateTime now = LocalDateTime.now();
        // 格式化当前时间的小时部分
//        LocalTime currentTime = now.toLocalTime();
        LocalDate localDate = LocalDate.now();
        LocalTime currentTime = LocalTime.now();
        DateTimeFormatter formatter=DateTimeFormatter.ofPattern("yyyy-MM-dd");

        List<Map<String, Object>> overdueReserves = reservationMainMapper.selectOverdueReserves();

        for(Map<String,Object> reserve:overdueReserves){
            Integer reserveId = (Integer)reserve.get("reserve_id");
            Integer maxEndHour = (Integer) reserve.get("max_end_hour");
            String reserveDateStr=(String)reserve.get("reserveDate");
            System.out.println(reserveDateStr);
            // 解析预约日期为LocalDate
            LocalDate reserveDate = LocalDate.parse(reserveDateStr, formatter);
            // 解析最大结束时间为LocalTime
            // 构建一个 “结束时间”（类型为LocalTime）。这里固定分钟为0，所以结果是 xx:00
            LocalTime endTime = LocalTime.of(maxEndHour, 0);
            // 如果结束日期在今天之前，则逾期。如果结束日期在今天，且结束时间在现在之前，则逾期
            Boolean isOverdue=reserveDate.isBefore(localDate)||(reserveDate.equals(localDate)&& endTime.isBefore(currentTime));
            // 已逾期
            if(isOverdue){
                LambdaUpdateWrapper<ReservationMain> wrapper = new LambdaUpdateWrapper<>();
                wrapper.eq(ReservationMain::getReserveId,reserveId)
                        .eq(ReservationMain::getReserveStatus,0)
                        .set(ReservationMain::getReserveStatus,3);

                reservationMainMapper.update(null,wrapper);
            }
//
        }

    }
}
